<template>
  <van-skeleton title :row="5" v-if="newsInfo === null" />
    <!-- <div class="content" v-else v-html="newsInfo.body" ></div> -->
 <!-- 文章主体内容 -->
 <van-skeleton title :row="4" v-if="newsInfo.length===0" />
 <van-skeleton title :row="5" v-if="newsInfo.length===0" />
  <div class="content" v-else>
    <div class="head_title">
        {{newsInfo.title}}
    </div>
      <div class="head_auth">
          <div class="img">
               <img :src="authorInfo.avatar" alt="">
          </div>
          <div class="Authinfo">
                <div class="author">{{authorInfo.name}}
                  <gh-icon name="user-zuanshi" class="zuanshi"></gh-icon>
                  <div class="exp"> Lv{{authorInfo.experience}}</div>
                </div>
                <div class="updated_time"><span>最后编辑时间：</span>{{convertDateToBeijingTime(newsInfo.updated_at)}}</div>
          </div>
          <div class="btn">
               <button @click="followConsultant(authorInfo.id)" >{{isFollow?'√ 已关注':'+ 关注' }} </button>
          </div>
      </div>
      <div class="article_pic">
          <img :src="newsInfo.picture" alt="">
      </div>
      <div class="article_content"> 
          {{newsInfo.content}}
          <div class="art_buttom">
              <span>编辑于湛江</span>
              <span> 
                 <gh-icon name="user-jubao" class="zuanshi"></gh-icon>
                 举报
              </span>
          </div>
      </div>
 </div>
  <div class="nav-box">
    <van-icon name="arrow-left" @click="handleBack" ></van-icon>
    <!-- 评论 -->
    <van-icon name="comment-o"
     :badge="store.comments"
     @click="commentHandle"
     ></van-icon>
     <!-- 评论弹窗列表 -->
     <van-popup
      class="comment-pop"
       v-model:show="showComments"
       round
      position="bottom"
      :style="{ height: '65%' }"
     >
       <div class="top-icon"> <span></span> </div>
       <div class="top-nav">
            <div class="comment-num">
                 <span class="l_com">全部评论</span>
                 <span class="r_com">{{store.comments}}</span>
            </div>
            <div class="comment-hotnew">
                <span class="l_hot active" @click="toggleHot()">最热</span>
                <span class="r_new" @click="toggleNew()">最新</span>
            </div>
       </div>
       <!-- 评论区内容 -->
       <div class="comments-content">
         <van-empty  v-if="commentsInfo.length===0"  description="暂无评论信息" />
           <div class="content-box" v-else>
                <div class="comment-item" v-for="item in commentsInfo" :key="commentsInfo.id">
                      <div class="avatar">
                          <img :src="item.avatar" alt="">
                      </div>
                      <div class="r_box">
                            <div class="top_info">
                                <div class="username">{{item.username}}</div>
                                <div class="sandian"> 
                                   <gh-icon name="user-sandian" class="good"></gh-icon>
                                </div>
                            </div>
                            <div class="comment-text">{{item.comment_text}}</div>
                            <div class="buttom-info">
                              <div class="l_b_info">
                                  <span>{{formatTimeDifference(item.comment_date)}} ·广东</span>
                                  <span class="huifu">回复</span>
                               </div>
                               <div class="r_b_info">
                                    <span class="good_sp"> 
                                      <gh-icon name="user-good" class="good"></gh-icon>
                                    </span>
                                    <span>  
                                       <gh-icon name="user-notgood" class="notgood"></gh-icon>
                                    </span>
                               </div>
                          </div>
                      </div>
                    </div>
                    <div class="more">没有了，客官~~~</div>
           </div>
       </div>
       <!-- 发送评论框 -->
       <div class="buttom-comment">
        <van-image round fit="cover" :src="avatar"  />
        <van-field
            v-model="message"
            placeholder="我来说两句..."
            clearable     
            autofocus
            @clear="clearInput"
            @keydown.enter="sendComment"
         >
      </van-field>
      <van-button type="primary" @click="sendComment">发送</van-button>
       </div>
    </van-popup>
    <!-- 点赞 -->
    <van-icon
     :name="isLike?'good-job':'good-job-o'  " 
     :color="isLike ? '#d81e06' : 'black'"
     :badge="store.likes"
     @click="likeHandle"
     ></van-icon>
     <!-- 收藏 -->
    <van-icon
    :name="isFavorite ? 'star' : 'star-o'"
    :color="isFavorite ? '#FACC3A' : 'black'"
      @click="storeHandle"
    ></van-icon>
    <!-- 分享 -->
    <van-icon name="share-o" color="#000"
    @click="shareHandle"
    ></van-icon>
    <van-share-sheet
    v-model:show="showShare"
    title="立即分享给好友"
    :options="options"
  />
  </div>
  
</template>

<script setup>
import {ref,reactive,onMounted,onBeforeMount,computed,onBeforeUnmount,onUpdated} from "vue"
import{useRouter,useRoute}from 'vue-router'
const router =useRouter();  
const route =useRoute()
import { Toast, Dialog, ShareSheet} from 'vant';
import 'vant/es/toast/style'
import { getImage,getUserInfo } from '@/services/user'
import {queryNewsStory,IsFavorite,IsLike,readHistory,getLikeNum,getcommentsNum,sendcomment, getcomments} from '@/services/article'
import{getArticleByid} from '@/services/consultant'
import{getconsultantInfoByName,getuseridByaccount} from '@/services/others'
import { useUserStore ,useArticleStore} from '@/stores'
// 响应变量存取用户数据
const userData=localStorage.getItem('gh-user')
// console.log(userData)
const userObj=JSON.parse(userData)
const userInfo=userObj.user.userData;
const user = ref({})
const avatar=ref()
//评论数
// const comments=ref(0)
//收藏数
// const popularity=ref(0)
const newsInfo=ref({})
//文章咨询师作者信息
const  authorInfo=ref({})
//用户id信息
const userId=ref('')
const store = useArticleStore()
const isFollow=ref(false)


//关注咨询师函数
const followConsultant=async(id)=>{
    isFollow.value=!isFollow.value
    if(isFollow.value==1){
         Toast.success('关注成功！')
    }
    else{
         Toast.success('取消关注！')
    }
    // console.log(id)
}
//立即分享
const showShare = ref(false);
    const options = [
      [
        { name: '微信', icon: 'wechat' },
        { name: '朋友圈', icon: 'wechat-moments' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
      ],
      [
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        { name: '小程序码', icon: 'weapp-qrcode' },
      ],
    ];
onBeforeMount(async()=>{
    // console.log(route.params.id)
    let id =route.params.id
    const res=await getArticleByid(id)
    // console.log(res.data)
    const info=await getconsultantInfoByName(res.data.author)
    // console.log(info.data)
    const account=JSON.parse(localStorage.getItem('gh-user')).user.userData.account
    const user_id=await getuseridByaccount(account)
    // console.log(user_id.data.id)
    //用户id数据
    userId.value=user_id.data.id
    // let res=await queryNewsInfo (id)
    //文章数据
    newsInfo.value=res.data
    //作者数据
    authorInfo.value=info.data
    //获取收藏状态
    const f_status=await IsFavorite(newsInfo.value.id,userId.value)
    // console.log(status.data.favorite_status)
    if(f_status.data.favorite_status==1){
       isFavorite.value=true
    }
    //获取点赞状态
    const l_status=await IsLike(newsInfo.value.id,userId.value)
    if(l_status.data.like_status==1){
       isLike.value=true
    }
    // console.log(newsInfo)
     // 动态创建CSS
    //  let link = document.createElement("link");
    //   link.id = "link";
    //   link.rel = "stylesheet";
    //   link.href =newsInfo.value.css[0];
    //   document.head.appendChild(link);
    //获取文章点赞和评论数
      let like_result=await getLikeNum(route.params.id)
      let comment_result=await getcommentsNum(route.params.id)
      // const store = useArticleStore()
      store.setArticleStory(like_result.data,comment_result.data)

    const pic= userInfo.avatar
    const Image=await getImage(pic)
    let imageData
  for(let i = 0; i < Image.data.base64Chunks.length; i++) {
    // 合并分块 Base64 数据
   const base64Data = Image.data.base64Chunks.join('');
    imageData = `data:image/jpeg;base64,${base64Data}`;
}
   avatar.value = imageData 
})
const convertDateToBeijingTime=(dateString) =>{
  // 创建一个新的 Date 对象，并将其设置为 UTC 时间
  const utcDate = new Date(dateString);
  // 将日期转换为北京时间，北京时间比 UTC 时间快 8 小时
  const beijingDate = new Date(utcDate.getTime() + 8 * 60 * 60 * 1000);
  // 格式化北京时间
  const formattedDate = `${beijingDate.getFullYear()}年${beijingDate.getMonth() + 1}月${beijingDate.getDate()}日`;
  return formattedDate;
}

// onUpdated(() => {
//       let imgPlaceHolder = document.querySelector(".img-place-holder");
//       if (imgPlaceHolder) {
//         if (imgPlaceHolder.innerHTML.trim() === "") {
//           imgPlaceHolder.innerHTML += `<img src="${newsInfo.image}" alt=""/>`;
//         }
//       }
//     });
onBeforeUnmount(async() => {
      // let link = document.getElementById("link");
      // if (!link) return;
      // document.head.removeChild(link);
      const formData=new FormData()
      formData.append('user_id',userId.value)
      formData.append('article_id',newsInfo.value.id)
      formData.append('title',newsInfo.value.title)
      formData.append('author',newsInfo.value.author)
      formData.append('picture',newsInfo.value.picture)
      const res=await readHistory(formData)
      // console.log(res.data)
    });
//处理返回
const handleBack=()=>{
    router.back()
}
  const isFavorite = ref(false);
  //禁止频繁点击收藏
  const isClickDisabled = ref(false);
  const isClickDisabled1= ref(false);
  // 处理点击收藏函数
  const storeHandle = async () => {
     if (isClickDisabled.value) {
        Toast('请勿重复点击');
      }
      else{
        if(isFavorite.value){
           // 如果已收藏，则取消收藏
           const article_id=newsInfo.value.id
           const user_id=userId.value
          //  const store = useArticleStore()
           store.removeFavorite(article_id,user_id)
           isFavorite.value=!isFavorite.value
        }
        else {
          // 如果未收藏，则收藏
          const article_id=newsInfo.value.id
          const user_id=userId.value
          // const store = useArticleStore()
           store.incrementFavorites(article_id,user_id)
           isFavorite.value=!isFavorite.value
        }
        isClickDisabled.value = true;
        setTimeout(() => {
          isClickDisabled.value = false;
        }, 3000);
       
      } 
  }

  const isLike=ref(false)
  //处理点赞喜欢函数
  const likeHandle=async ()=>{
     if(isClickDisabled1.value) {
        Toast('请勿重复点击');
      }
      else{
        if(isLike.value){
           // 如果已收藏，则取消收藏
           const article_id=newsInfo.value.id
           const user_id=userId.value
          //  const store = useArticleStore()
           store.removeLike(article_id,user_id)
           isLike.value=!isLike.value
        }
        else {
          // 如果未收藏，则收藏
          const article_id=newsInfo.value.id
          const user_id=userId.value
          // const store = useArticleStore()
           store.incrementLikes(article_id,user_id)
           isLike.value=!isLike.value
        }
        isClickDisabled1.value = true;
        setTimeout(() => {
          isClickDisabled1.value = false;
        }, 3000);
       
      } 
  }
  
  //所有评论信息
  const commentsInfo=ref([])
  const showComments=ref(false)
  //处理点击评论函数
  const commentHandle=async()=>{
      showComments.value=true
      fetchComments()
  }
  
  //点击分享处理函数
  const shareHandle=async()=>{
       showShare.value=true
  }

  //评论语句
const message=ref('')
 //发送评论函数
 const sendComment=async()=>{
  if (message.value.trim() !== '') {
        // 执行发送消息的操作
        console.log(message.value)
        const formData=new FormData()
       formData.append('article_id',newsInfo.value.id)
       formData.append('user_id',userId.value)
       formData.append('comment_text',message.value)
       const res=await sendcomment(formData)
       if(res.status==201){
        fetchComments()
        const like_result=await getLikeNum(route.params.id)
        const comment_result=await getcommentsNum(route.params.id)
      // const store = useArticleStore()
       store.setArticleStory(like_result.data,comment_result.data)

       }
       else{
          Toast('网络糟糕~~~')
       }
        // console.log(res.data)
      }
      // 清空输入框
     clearInput();
   
 }
 const clearInput=() =>{
      // 清空输入框
     message.value = '';
}
  //切换到最热评论函数
  function toggleHot() {
    document.querySelector('.l_hot').classList.add('active');
    document.querySelector('.r_new').classList.remove('active');
}
  //切换到最新评论函数
  function toggleNew() {
    document.querySelector('.r_new').classList.add('active');
    document.querySelector('.l_hot').classList.remove('active');
}
//评论区显示时间点
function formatTimeDifference(targetTime) {
    const targetDate = new Date(targetTime);
    const currentDate = new Date();
    const timeDiff = (currentDate - targetDate) / (1000 * 60); // 时间差（分钟）

    if (timeDiff < 1) {
        return "刚刚";
    } else if (timeDiff < 30) {
        return `${Math.floor(timeDiff)}分钟前`;
    } else if (timeDiff < 1440) { // 30分钟以上，即30 * 60 = 1440分钟
        const hh = targetDate.getHours().toString().padStart(2, '0');
        const mm = targetDate.getMinutes().toString().padStart(2, '0');
        return `今天 ${hh}:${mm}`;
    } else if (isSameDay(targetDate, currentDate.setDate(currentDate.getDate() - 1))) {
        const hh = targetDate.getHours().toString().padStart(2, '0');
        const mm = targetDate.getMinutes().toString().padStart(2, '0');
        return `昨天 ${hh}:${mm}`;
    } else {
        const month = targetDate.getMonth() + 1;
        const date = targetDate.getDate();
        const hh = targetDate.getHours().toString().padStart(2, '0');
        const mm = targetDate.getMinutes().toString().padStart(2, '0');
        return `${month}-${date} ${hh}:${mm}`;
    }
}

function isSameDay(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
}

const fetchComments=async()=>{
    const res=await  getcomments(newsInfo.value.id)
    const rows=res.data
    rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.avatar;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.avatar = imageData;
    }
  });
    commentsInfo.value=rows
}

</script>

<style lang="scss" scoped>
.content{
  width: 100%;
    .head_title{
      padding: 10px 20px;
       font-size: 18px;
       font-weight: bold;
       line-height: 25px;
       width: 100%;
       font-family: '黑体';
       letter-spacing: 2px;
    }
    .head_auth{
        width: 100%;
        height: 60px;
        align-items: center;
        position: relative;
        display: flex;
        .img{
            padding: 10px 15px;
             img{
                display: block;
                height: 40px;
                width: 40px;
                border-radius: 20px;
             }
        }
        .Authinfo{
            height: 100%;
            margin-top: 20px;
            font-family: '黑体';
            .author{
              display: flex;
              align-items: center;
              font-size: 16px;
              color: #BCA480;
              .zuanshi{
                font-size: 12px;
                margin: 0 3px;
              }
              .exp{
                font-size: 10px;
                width: 35px;
                text-align: center;
                border-radius: 10px;
                color: #768DA1;
                background-color: #E1F8FF;
              }
            }
            .updated_time{
               font-size: 11px;
               margin-top: 4px;
               color: #C6C6C6;
            }
        }
        .btn{
               right: 20px;
               text-align: center;
               position: absolute;
               button{
                 width: 80px;
                 height: 30px;
                 background-color: #345BF3;
                 color: #fff;
                 font-size: 14px;
                 font-family: '黑体';
                 border-radius: 5px;
                 border: none;
               }
            }
    }
    .article_pic{
        width: 100%;
        height: 200px;
        margin:20px 0 10px;
        img{
            display: block;
            width: 100%;
            height: 100%;
            border-radius: 30px;
        }
    }
    .article_content{
       width: 100%;
       text-indent: 2em;
       padding: 5px 10px 20px;
       margin-bottom: 50px;
       font-family: '黑体';
       letter-spacing: 3px;
       font-size: 16px;
       line-height: 25px;
       .art_buttom{
          margin-top: 10px;
          font-size: 12px;
          color: #C6C6C6;
          display: flex;
          text-indent: 0em;
          justify-content: space-between;
          font-family: '宋体';
       }
    }
  }
.van-skeleton {
  padding: 30px 15px;
}

.nav-box{
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    width: 100%;
    box-sizing: border-box;
    justify-content: space-between;
    padding: 0 20PX;
    height: 50PX;
    align-items: center;
    background:#F4F4F4;
    font-size: 20px;
    .van-icon:nth-child(1){
        position: relative;
        &::after{
        right: -15px;
        position: absolute;
        content: '';
        top: -5%;
        width: 1px;
        height: 120%;
        background: #d5d5d5;
        }
    }
    :deep .van-badge{
        background-color: transparent;
        border:none;
        color: #BCA480;
        right: -10px;
        font-size: 12px;
        font-weight: bold;
    }
     .comment-pop{
          width:100%;
          position: relative;
          .top-icon{
               position: sticky;
               z-index: 1;
               top: 0;
               left: 0;
               border-radius: 18px 18px 0 0;
               width: 100%;
               height: 30px;
               display: flex;
               align-items: center;
               background-color: #fff;
               justify-content: center;
               span{
                   display: block;
                   height: 3px;
                   width: 40px;
                   border-radius: 5px;
                   background-color: gray;
               }
           }
          .top-nav{
             z-index: 1;
             position: sticky;
             background-color: #fff;
             top: 30px;
             left: 0;
             width: 100%;
             height: 40px;
             display: flex;
             justify-content: space-between;
             align-items: center;
             padding: 10px 10px;
             .comment-num{
                 .l_com{
                     font-size: 16px;
                     font-weight: bold;
                 }
                 .r_com{
                     margin-left: 5px;
                     font-size: 14px;
                     font-weight: bold;
                 }
             }
             .comment-hotnew{
                 font-size: 12px;
                 font-family: '黑体';
                 position: relative;
                 background-color:#C6C6C6;
                 height:20px;
                 width: 80px;
                 border-radius: 8px;
                 display: flex;
                 justify-content: space-between;
                 .l_hot,.r_new{
                       width: 40px;
                       height: 20px;
                       color: #fff;
                       cursor: pointer;
                       padding:0 8px;
                 }
                 .active{
                          background-color: #fff; /* 激活颜色 */
                          color: #000; /* 激活字体颜色 */
                          border-radius: 8px;
                          /* width: 40px;
                          height: 20px; */
                          transition: all 0.3s;
                       }
                
               }
            }
          .comments-content{
            width: 100%;
            /* background-color: #C6C6C6; */
            height: calc(65vh - 134px); /* 100px 是顶部和底部的高度之和 */
            overflow-y: auto; /* 启用垂直滚动条 */
            padding: 10px;
            .content-box{
               width: 100%;
                 .comment-item{
                    width: 100%;
                    margin-bottom: 10px;
                    display: flex;
                    position: relative;
                    &::after{
                      content: '';
                      position: absolute;
                      bottom: 0;
                      left: 50%;
                      transform: translate(-50%);
                      width: 80%;
                      height: 1px; /* 设置横线的高度 */
                      background-color: #E1F8FF; /* 设置横线颜色 */
                    } 
                      .avatar{
                          width: 45px;
                          padding-top: 6px;
                          img{
                             display: block;
                             width: 30px;
                             height: 30px;
                             border-radius: 15px;
                          }
                      }
                      .r_box{
                          flex: 1;
                          display: flex;
                          flex-direction: column;
                          .top_info{
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            padding-bottom: 5px;
                             .username{
                              font-size: 12px;
                              font-family: '黑体';
                              color: red;
                             }
                             .sandian{
                                font-size: 14px;
                             }
                          }
                          .comment-text{
                             font-size: 14px;
                             padding-right: 15px;
                             width: 100%;
                             overflow: hidden;
                             letter-spacing: 1px;
                             line-height: 20px;
                             font-family: '黑体';
                          }
                          .buttom-info{
                             height: 35px;
                             width: 100%;
                             padding: 8px 10px 10px 0;  
                             display: flex;
                             justify-content: space-between;
                             align-items: center;
                             font-size: 10px;
                             color: #C6C6C6;
                             .l_b_info{
                                 min-width: 120px;
                                 max-width: 180px;
                                 display: flex;
                                 justify-content: space-between;
                                 align-items: center;
                                }
                             .r_b_info{
                                min-width: 45px;
                                height: 100%;
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                font-size: 14px;
                                .good_sp{
                                   padding: 0 5px;
                                }
                             }
                          }
                      }
                 }
                 .more{
                   font-size: 12px;
                   font-family: '黑体';
                   text-align: center;
                   color: #C6C6C6;
                 }
            }


          }
          .buttom-comment{
             position: sticky;
             width: 100%;
             height: 60px;
             border-bottom: 4px solid #fff;
             text-align: center;
             display: flex;
             align-items: center;
             background-color: #fff;
             justify-content: space-between;
             padding: 0 10px;
             bottom: 0;
             left: 0;
             .van-image {
                 width: 40px;
                 height: 40px;
              }
             .van-field {
                  flex: 1;
                  margin: 0 10px;
                  height: 40px;
                  padding:20px;
                  background-color: #F4F4F4;
                  border-radius: 10px;
                  display: flex;
                  align-items: center;
                  .van-field__value{
                      padding-left: 20px;
                  }
                }
             .van-button {
                   width: 60px;
                   padding: 0;
                   font-size: 13px;
                   letter-spacing: 3px;
                   height: 30px;
                   border-radius: 10px;
                 }
            }
     }
}

</style>
